/**
 *区域查询
 */
'use strict';

const conn = require('../../libs/DB/Conn');
const _ = require('underscore');


module.exports = async function (params) {

   let domainList = await conn(`
                                 SELECT
                                     df.domain_id AS domainId,
                                     df.domain_name AS domainName,
                                     drf.district_name AS regionName,
                                     drf.district_id AS districtId,
                                     dcf.district_name AS cityName,
                                     dcf.district_id AS cityId,
                                     dpf.district_name AS provinceName,
                                     dpf.district_id AS provinceId,
                                     df.address,
                                     df.manager_name AS managerName,
                                     df.manager_mobile AS managerMobile,
                                     dc.lng,
                                     dc.lat
                                 FROM domain_file df
                                 INNER JOIN agent_file af ON af.agent_id = df.agent_id AND af.delete_sign = 1 AND df.agent_id = ${params.userAgentId} 
                                 INNER JOIN district_file drf ON drf.district_id = df.district_id ${params.districtId ? `AND drf.district_id = ${params.districtId}` : ""} 
                                 INNER JOIN district_file dcf ON dcf.district_id = drf.parent_id ${params.cityId ? `AND dcf.district_id = ${params.cityId}` : ""} 
                                 INNER JOIN district_file dpf ON dpf.district_id = dcf.parent_id ${params.provinceId ? `AND dpf.district_id = ${params.provinceId}` : ""} 
                                 LEFT JOIN domain_coordinate dc ON dc.domain_id = df.domain_id
                                 WHERE
                                    df.delete_sign = 1`);
   let domainGroup = _.groupBy(domainList,"domainId");
   let dataList = [];
   for(const domainId in domainGroup){
      let domainPointList = domainGroup[domainId];
      let pointList = [];
      if(domainPointList[0].lng && domainPointList[0].lat){
         for(const domainPoint of domainPointList){
            pointList.push([domainPoint.lng,domainPoint.lat]);
         }
      }
      delete domainPointList[0].lng;
      delete domainPointList[0].lat;
      domainPointList[0].pointList = pointList;
      dataList.push(domainPointList[0]);
   }

   return {success:true,dataList:dataList};
};
